package com.usernet.product.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.usernet.product.comm.BaseDao;
import com.usernet.product.entity.Admin;
import com.usernet.product.tools.AdminRight;
import com.usernet.product.utils.Page;
import com.usernet.product.utils.PageResult;
import com.usernet.product.utils.ProductConfig;
import com.usernet.product.utils.ProductUtils;

public class AdminDao extends BaseDao {
	/*
	 * return
	 * "adminId"：登录成功，"-1"：用户名不存在，"-2"：密码错误，"-3"：用户不可用，"throw exception"：服务器错误
	 */
	@SuppressWarnings("unchecked")
	public int login(String loginName, String password) {
		Session session = getSession();
		String hql = "from Admin where loginName=:loginName";
		Transaction tr = null;
		try {
			tr = session.beginTransaction();
			Query query = session.createQuery(hql);
			query.setString("loginName", loginName);
			List list = query.list();
			tr.commit();
			Admin admin = null;
			if (list.size() > 0)
				admin = (Admin) list.get(0);
			if (admin == null) {
				return -1;
			}
			if (!admin.getPassword()
					.equals(password)) {
				return -2;
			} else if (admin.getStatus() == ProductConfig.DIS_STATUS) {
				return -3;
			} else {
				return admin.getId();
			}
		} catch (HibernateException e) {
			if (tr != null) {
				tr.rollback();
			}
			throw e;
		}
	}
	/** 检查登录名是否存在 */
	@SuppressWarnings("unchecked")
	public boolean checkLoginName(String loginName) {
		Session session = getSession();
		String hql = "from Admin where loginName=:loginName";
		Transaction tr = null;
		try {
			tr = session.beginTransaction();
			Query query = session.createQuery(hql);
			query.setString("loginName", loginName);
			List list = query.list();
			tr.commit();
			if (list.size() > 0)
				return true;
			return false;
		} catch (HibernateException e) {
			if (tr != null) {
				tr.rollback();
			}
			throw e;
		}
	}

	/** 锁定用户 */
	public void lockUser(String loginName) {
		Session session = getSession();
		String hql = "update Admin set status=:status where loginName=:loginName";
		Transaction tr = null;
		try {
			tr = session.beginTransaction();
			Query query = session.createQuery(hql);
			query.setInteger("status", ProductConfig.DIS_STATUS);
			query.setString("loginName", loginName);
			query.executeUpdate();
			tr.commit();
		} catch (HibernateException e) {
			if (tr != null) {
				tr.rollback();
			}
		}
	}

	@SuppressWarnings("unchecked")
	public PageResult<Admin> getAllByPage(Page page) {
		String hql = "from Admin where flag!=" + AdminRight.supers
				+ " order by id";
		return super.getAllByPageAndHql(page, hql);
	}
}
